package org.aristotle.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.aristotle.auth.constant.SysAuthConstant;
import org.aristotle.common.utils.AristotleBeanUtils;
import org.aristotle.user.model.dto.PermissionDTO;
import org.aristotle.user.model.entity.Role;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
// 本模块
import org.aristotle.user.model.entity.Permission;
import org.aristotle.user.model.vo.PermissionVO;
import org.aristotle.user.mapper.PermissionMapper;
import org.aristotle.user.service.IPermissionService;

// 一对多(本类是多)
// 多对一(本类是多)
// 多对多关系
import org.aristotle.user.model.entity.RolePermission;
import org.aristotle.user.service.IRolePermissionService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    // 多对一(本类是多)

    // 一对多(本类是一)

    // 多对多关系中间表
    @Autowired
    private IRolePermissionService rolePermissionService;

    @Override
    public Page<PermissionVO> queryPageList(
        Long id,
        String name,
        String identifier,
        Integer current,
        Integer size
    ) {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper();

        if (id != null) {
            queryWrapper.eq("id",id);
        }

            if (!StringUtils.isBlank(name)) {
                queryWrapper.like("name",name);
            }
            if (!StringUtils.isBlank(identifier)) {
                queryWrapper.like("identifier",identifier);
            }


        Page<Permission> page = this.page(new Page<Permission>(current,size), queryWrapper);

        // 转为VO
        Page<PermissionVO> result = AristotleBeanUtils.transitionBean(page, Page<PermissionVO>::new);
        result.setRecords(AristotleBeanUtils.copyListProperties(page.getRecords(),PermissionVO::new));

        result.getRecords().forEach(permissionVO -> {
            // 多对一(本类是多)
        });
        return result;
    }

    @Override
    public PermissionVO getById(Long id) {
        Permission permission = this.baseMapper.selectById(id);
        PermissionVO permissionVO = AristotleBeanUtils.transitionBean(permission, PermissionVO::new);
        return permissionVO;
    }

    @Override
    @Transactional
    public Boolean removeById(Long id) {
        /*删除中间表*/
        QueryWrapper<RolePermission> queryWrapperRolePermission = new QueryWrapper<>();
        queryWrapperRolePermission.eq("permission_id",id);
        rolePermissionService.remove(queryWrapperRolePermission);
        /*一对多(本类是一)*/

        return super.removeById(id);
    }

    @Override
    public PermissionDTO getDTOById(Long permissionId) {
        Permission permission = super.getById(permissionId);
        return permissionPOToDTO(permission);
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Boolean refreshAuthRule() {
        // 清缓存
        redisTemplate.delete(SysAuthConstant.OAUTH_URLS);
        List<Permission> permissions = this.list();
        Map<String,List<String>> map = new HashMap<>();
        permissions.stream().forEach(permission -> {

            String url = permission.getMethod() + SysAuthConstant.METHOD_SUFFIX + permission.getUrl();

            List<Role> roles = rolePermissionService.getRoleByPermissionId(permission.getId());
            if (roles == null||roles.size() == 0) {
                return;
            }
            List<String> roleIdentifiers = roles.stream().map(role -> SysAuthConstant.ROLE_PREFIX + role.getIdentifier()).collect(Collectors.toList());

            map.put(url,roleIdentifiers);
        });
        // 添加缓存
        redisTemplate.opsForHash().putAll(SysAuthConstant.OAUTH_URLS,map);
        return true;
    }

    private PermissionDTO permissionPOToDTO(Permission permission) {
        PermissionDTO permissionDTO = new PermissionDTO();
        BeanUtils.copyProperties(permission,permissionDTO);
        return permissionDTO;
    }

}
